package com.neusoft.my12306.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.my12306.common.res.CommonResult;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.MalformedJwtException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

public class AuthTokenFilter implements Filter {
    private JwtUtil jwtUtil;

    public void setJwtUtil(JwtUtil jwtUtil) {
        System.out.println("成功注入JwtUtil");
        this.jwtUtil = jwtUtil;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
//        获得headers中数据
//        Enumeration<String> headerNames = request.getHeaderNames();
//        for (  ; headerNames.hasMoreElements(); ){
//            String key = headerNames.nextElement();
//
//             String value =  request.getHeader(key);
//
//            System.out.println( key +  ":" + value);
//        }
//        String token =  request.getHeader("authorization");
//        Claims claims = null;
//        try {
//              claims =  jwtUtil.parseJWT(token);
//        }catch ( MalformedJwtException ex   ){
//            CommonResult  result =new CommonResult(408,"所携带的Token异常",null);
//            ObjectMapper mapper = new ObjectMapper ();
//            String json =  mapper.writeValueAsString(result);
//            response.getWriter().append(json).flush();
//            return;
//        }catch ( Exception ex   ){
//            CommonResult  result =new CommonResult(408,"所携带的Token异常",null);
//            ObjectMapper mapper = new ObjectMapper ();
//            String json =  mapper.writeValueAsString(result);
//            response.getWriter().append(json).flush();
//            return;
//        }
//        if(  claims.getExpiration().getTime() < System.currentTimeMillis()){
//            CommonResult  result =new CommonResult(409,"所携带的Token过期",null);
//            ObjectMapper mapper = new ObjectMapper ();
//            String json =  mapper.writeValueAsString(result);
//            response.getWriter().append(json).flush();
//            return;
//        }
        chain.doFilter(request,response);
    }
}
